package org.example.imageservice.Impl;
import org.example.imageservice.service.BgimageService;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class BgimageServiceImpl implements BgimageService {

    private final ResourceLoader resourceLoader;

    public BgimageServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public List<String> getImages( String classpath,String  imageUrl0) throws IOException {
        List<String> images = new ArrayList<>();
        Resource resource = resourceLoader.getResource(classpath);
        File sourceDir = resource.getFile();
        File[] files = sourceDir.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && isImageFile(file.getName())) {
                    String imageUrl = imageUrl0 + file.getName();
                    images.add(imageUrl);
                    // 找到一个图片文件就直接返回
                    if (!classpath.equals("classpath:static/swiper/")){
                        return images;
                    }

                }
            }
        }
        // 如果没有找到图片文件，则返回空列表
        return images;
    }


    public ResponseEntity<?> uploadFile(MultipartFile uploadfile,String classpath) throws IOException {
        if (uploadfile.isEmpty()) {
            return new ResponseEntity<>("请选择一个文件！", HttpStatus.OK);
        } else {
            try {
                saveUploadedFiles(uploadfile,classpath);
            } catch (Exception e) {
                return new ResponseEntity<>("文件上传失败！",HttpStatus.BAD_REQUEST);
            }
        }
        return new ResponseEntity<>("文件上传成功！", HttpStatus.OK);
    }
    private void saveUploadedFiles(MultipartFile file,String classpath) throws Exception {
        // 获取static/source文件夹的绝对路径
        Resource resource = resourceLoader.getResource(classpath);
        File sourceDir = resource.getFile();

        if (classpath.equals("classpath:static/index-background/")){
            // 扫描目标文件夹中的文件
            Path path = Paths.get(sourceDir.getPath());
            DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path);
            Iterator<Path> iterator = directoryStream.iterator();
            // 删除旧文件
            while (iterator.hasNext()) {
                Path oldFile = iterator.next();
                if (!oldFile.getFileName().toString().equals(file.getOriginalFilename())) {
                    Files.delete(oldFile);
                }
            }
            directoryStream.close();
        }

        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(sourceDir + "/" + file.getOriginalFilename());
            System.out.println(path);
            Files.write(path, bytes);
        }


    }

    public ResponseEntity<String> deleteImage(String imageUrl) {
        try {
            // 根据图片 URL 获取本地文件路径（这里假设图片存储在 static/swiper 目录下）
            Path imagePath = Paths.get(imageUrl).getParent().resolve("static/swiper");
            // 检查文件是否存在，如果存在则删除
            if (Files.exists(imagePath)) {
                Files.delete(imagePath);
                return new ResponseEntity<>("Image deleted successfully.", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("Image does not exist.", HttpStatus.NOT_FOUND);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Error deleting image.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 判断文件名是否为图片文件，这里只判断了四种常见的图片格式
    public boolean isImageFile(String fileName) {
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ||fileName.endsWith(".webp") ||
                fileName.endsWith(".png") || fileName.endsWith(".gif")) {
            return true;
        }
        return false;
    }
}
